package org.apache.zookeeper.recipes;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.retry.RetryNTimes;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <h2></h2>
 * description: 使用场景：从连接到zk集群的一组竞争者中选出一个leader，
 * 多个竞争者竞争一个leadership，将会随机分配给一个竞争者，直到它释放leadership，此时将会从组中随机选择另一个。
 *
 *
 * @author yongjun.ji(yongjun.ji @ ucarinc.com)
 * @since 1.0 2020/6/15 14:58
 */
public class LeaderLatchDemo {
    public static void main(String[] args) throws Exception {
        int count = 10;
        List<LeaderLatch> leaderLatches = new ArrayList<>(count);
        List<CuratorFramework> clients = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", new RetryNTimes(3, 100));
            client.start();
            clients.add(client);

            LeaderLatch leaderLatch = new LeaderLatch(client, "/leaderLatch", "leaderLatch:" + i);
            leaderLatch.start();
            leaderLatches.add(leaderLatch);
        }

        System.out.println("等待选举");

        TimeUnit.SECONDS.sleep(5);

        System.out.println("查看选举结果");
        for (LeaderLatch leaderLatch : leaderLatches) {
            if (leaderLatch.hasLeadership()) {
                System.out.println(leaderLatch.getLeader().getId());
                leaderLatch.close();
            }
        }

        TimeUnit.SECONDS.sleep(3);

        for (LeaderLatch leaderLatch : leaderLatches) {
            if (leaderLatch.hasLeadership()) {
                System.out.println(leaderLatch.getLeader().getId());
                leaderLatch.close();
            }
        }


        System.in.read();

        for (CuratorFramework client : clients) {
            client.close();
        }

    }
}
